package name.jiaosha.air.iostorage.service.impl;

import java.util.Date;
import java.util.List;

import name.jiaosha.air.AppConstants;
import name.jiaosha.air.constant.DocID;
import name.jiaosha.air.iostorage.dao.IBuyDao;
import name.jiaosha.air.iostorage.dao.IBuyItemDao;
import name.jiaosha.air.iostorage.domain.Buy;
import name.jiaosha.air.iostorage.domain.BuyItem;
import name.jiaosha.air.iostorage.service.IStorageService;
import name.jiaosha.air.system.dao.IDocIDFactoryDao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ali8ba.common.PageInfo;

@Service
public class StorageService implements IStorageService {

	@Autowired
	private IBuyDao buyDao;

	@Autowired
	private IDocIDFactoryDao docIDFactoryDao;

	@Autowired
	private IBuyItemDao buyItemDao;

	@Override
	public void createBuy(Buy buy) {

		buy.setCreateTime(new Date());
		buy.setDocID(docIDFactoryDao.getDocIDByComIdAndType(AppConstants.comId,
				DocID.InStorage));
		buyDao.save(buy);
		for (BuyItem item : buy.getItems()) {

			item.setDocID(buy.getDocID());
			item.setSurplus(item.getAmount());
			buyItemDao.save(item);

		}

	}

	@Override
	public Buy getBuyById(String id) {

		return buyDao.get(id);
	}

	@Override
	public PageInfo<Buy> getBuyListByComId(Integer comId, int index,
			int pageSize) {

		String jpql = "SELECT b FROM Buy b";

		return buyDao.findForPage(jpql, index, pageSize, null);
	}

	@Override
	public Buy updateBuy(Buy buy) {
		return buyDao.saveOrUpdate(buy);

	}

	@Override
	public List<BuyItem> getBuyItems(String docID) {

		String jpql = "SELECT b FROM BuyItem b WHERE b.docID=?1";
		return buyItemDao.find(jpql, docID);
	}

}
